<?php

namespace app\admin\controller\catefrogood;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;


/**
 * 分类管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Index模型对象
     * @var \app\admin\model\catefrogood\Index
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\catefrogood\Index;


        $list = Db::name('catefrogood')->where('pid','eq',0)->select();

        // 初始化树状结构
        Tree::instance()->init($list);

        // 获取树状结构数据
        $treeArray = Tree::instance()->getTreeArray(0);

        // 筛选只保留一级和二级分类
        $groupdata = [];
        $groupdata['0'] = '无'; // 添加一个默认选项
        foreach ($treeArray as $v) {

                $groupdata[$v['id']] =  $v['name']; // 添加缩进以区分层级

        }

        // 将数据传递到视图
        $this->view->assign('categoryList', $groupdata);


    }


    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        //判断请求为Ajax
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //查询数据库获得结果
            $list = $this->model
                ->where($where)
                ->order('weigh desc')
                ->select();
            //遍历对数据的可见性设置
            foreach ($list as $row) {
                $row->visible(['id','name','image','update_time','createtime','status']);

            }


            Tree::instance()->init($list);
            $treeArray = Tree::instance()->getTreeArray(0); // 应该返回树形结构
            $result1 = Tree::instance()->getTreeList($treeArray);


            $result = array("total"=>count($list),"rows"=>$result1);
            //返回
            return json($result);



            //初始化并传入结果
            Tree::instance()->init($list);
            $groupdata = [];
            //获取树形结构列表
            $result1 = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            //返回值
            $result = array("total"=>$list->total(),"rows"=>$result1);
            //返回
            return json($result);
        }
        return $this->view->fetch();
    }


}
